package com.destin.basic.util;

import com.destin.basic.config.RedisUtils;
import com.destin.basic.constans.RedisKey;
import com.destin.basic.security.LoginUserInfo;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author ：destin
 * @date ：2022-03-23
 * @version: V1.0
 * @description: 获取当前用户信息工具类
 **/
public class UserUtils {

    public static final ThreadLocal<String> userId = new ThreadLocal<>();

    public static LoginUserInfo getConcurrentUser() {
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        return (LoginUserInfo) redisUtils.get(RedisKey.getLoginUserKey(getUserName()));
    }

    private static String getUserCard() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        authentication = Optional.ofNullable(authentication).orElse(new UsernamePasswordAuthenticationToken("", ""));
        String userCard = (String) authentication.getPrincipal();
        return userCard;
    }
    public static String getUserId(){
        return getConcurrentUser().getId();
    }

    public static String getUserName(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        authentication = Optional.ofNullable(authentication).orElse(new UsernamePasswordAuthenticationToken("", ""));
        return JwtTokenUtils.getUsername(authentication.getCredentials().toString());
    }
}
